import 'package:dio/dio.dart';
import 'package:enjoy_plus_community/utils/eventbus.dart';
import 'package:enjoy_plus_community/utils/http.dart';
import 'package:enjoy_plus_community/utils/toast.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';

class ProfilePage extends StatefulWidget {
  ProfilePage({super.key, required this.userInfo});

  Map userInfo;

  @override
  State<ProfilePage> createState() => _ProfilePageState();
}

class _ProfilePageState extends State<ProfilePage> {
  Map userInfo = {'avatar': null, 'nickName': null, 'id': ''};

  TextEditingController _controller = TextEditingController();

  @override
  void initState() {
    super.initState();
    setState(() {
      userInfo = widget.userInfo;
      _controller.text = userInfo['nickName'] ?? '';
    });
  }

  void updateNickname() async {
    String nickName = _controller.text;
    if (nickName.isEmpty) return ToastUtil.showError('昵称不能为空');
    if (nickName.length > 10) return ToastUtil.showInfo('昵称不能超过10个字符');
    await http.put('/userInfo', data: {'nickName': nickName});
    ToastUtil.showSuccess('昵称修改成功');
  }

  void showImageSheet() {
    showModalBottomSheet(
      context: context,
      builder: (context) {
        return SizedBox(
          height: 180,
          child: Column(
            children: [
              ListTile(
                leading: const Icon(Icons.camera_alt),
                title: const Text('拍照'),
                onTap: () async {
                  ImagePicker picker = ImagePicker();
                  final XFile? photo = await picker.pickImage(
                    source: ImageSource.camera,
                  );
                  if (photo != null) {
                    uploadAvatar(photo.path);
                  }
                },
              ),
              ListTile(
                leading: const Icon(Icons.photo),
                title: const Text('相册'),
                onTap: () async {
                  ImagePicker picker = ImagePicker();
                  final XFile? image = await picker.pickImage(
                    source: ImageSource.gallery,
                  );
                  if (image != null) {
                    uploadAvatar(image.path);
                  }
                },
              ),
            ],
          ),
        );
      },
    );
  }

  uploadAvatar(String imagePath) async {
    Navigator.pop(context);
    FormData formData = FormData.fromMap({
      "file": await MultipartFile.fromFile(imagePath),
      "type": "avatar",
    });
    final res = await http.post('/upload', data: formData);
    if (res['code'] != 10000) return ToastUtil.showError('上传图片失败!');
    setState(() {
      userInfo['avatar'] = res['data']['url'];
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: const Text('个人信息'),
        backgroundColor: Colors.transparent,
        centerTitle: true,
        leading: IconButton(
          onPressed: () {
            eventBus.fire(UpdateNickname());
            Navigator.pop(context);
          },
          icon: Icon(Icons.arrow_back),
        ),
      ),
      body: ListView(
        padding: const EdgeInsets.all(10),
        children: [
          SizedBox(
            height: 40,
            child: Row(
              children: [
                const Text('头像', style: TextStyle(fontSize: 16)),
                const Spacer(),
                Row(
                  children: [
                    GestureDetector(
                      onTap: () {
                        showImageSheet();
                      },
                      child: ClipRRect(
                        borderRadius: BorderRadius.circular(50.0),
                        child: userInfo['avatar'] == null
                            ? Image.asset(
                                'images/avatar_1.jpg',
                                width: 30,
                                height: 30,
                              )
                            : Image.network(
                                userInfo['avatar'],
                                width: 50,
                                height: 50,
                              ),
                      ),
                    ),
                    const Icon(Icons.arrow_forward_ios, size: 12),
                  ],
                ),
              ],
            ),
          ),
          Row(
            children: [
              const Text('昵称'),
              const Spacer(),
              Expanded(
                child: TextField(
                  controller: _controller,
                  decoration: const InputDecoration(
                    hintText: '请输入昵称',
                    border: InputBorder.none,
                  ),
                  textAlign: TextAlign.right,
                  onEditingComplete: () {
                    updateNickname();
                  },
                ),
              ),
              const Icon(Icons.arrow_forward_ios, size: 12),
            ],
          ),
        ],
      ),
    );
  }
}
